//
//  TweetsViewController.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-3-12.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "TweetsViewController.h"

#import "TwitterClient.h"
#import "Tweet.h"

#import "DataManager.h"

#import "ViewControllerChooser.h"

#import "ProfileImageProcesser.h"

#import "PImage.h"

#import "CustomCellMaker.h"

#import "GTMBase64.h"


@implementation TweetsViewController

@synthesize deflogo;
@synthesize favNOImage;
@synthesize favYESImage;
@synthesize fetchedResultsController;

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/

- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.navigationController.tabBarItem.title = @"Friends";
	
	tweets = [[NSMutableArray alloc] init];
	
	
	
	
	DataManager *dm = [DataManager sharedManager];
	self.fetchedResultsController = [dm fetchedResultsControllerForName:@"Tweet" withSortKey:@"tid"];
	
	NSError *error = nil;
	if (![fetchedResultsController performFetch:&error]) {
		/*
		 Replace this implementation with code to handle the error appropriately.
		 
		 abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
		 */
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		abort();
	}
	NSArray *fobjs = fetchedResultsController.fetchedObjects;
	if(fobjs && ([fobjs count] > 0)){
		NSInteger unlen = 0;
		NSInteger len = [fobjs count];
		[tweets addObjectsFromArray:fobjs];
		Tweet *tw = (Tweet *)[fobjs objectAtIndex:0];
		lastID = tw.tid;
		for(int i = 0;i<len;i++){
			tw = (Tweet *)[fobjs objectAtIndex:i];
			if([tw.unreaded boolValue]){
				unlen++;
			}
		}
		if(unlen > 0){
			self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",unlen];
		}
	}
	
	pp = [ProfileImageProcesser getInstance];
	pp.delegate = self;
	//[pp loadImagesFromData];
	
	[pp putImage:@"twitterdeflogo" withImage:self.deflogo];
	NSBundle *mainBundle = [NSBundle mainBundle];
	NSString *logoPath = [mainBundle pathForResource:@"fav1" ofType:@"png"];
	UIImage *img = [[UIImage alloc] initWithContentsOfFile:logoPath];
	self.favNOImage = img;
	[img release];
	
	logoPath = [mainBundle pathForResource:@"fav2" ofType:@"png"];
	img = [[UIImage alloc] initWithContentsOfFile:logoPath];
	self.favYESImage = img;
	[img release];
	
	
	self.tableView.rowHeight = 90.0;
	
	self.tableView.backgroundColor = [UIColor lightGrayColor];
	
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	self.tabBarController.navigationItem.title = @"Friends";
	
	// UIBarButtonItem *breload = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reload:)];
	breload = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reload:)];
	
	self.tabBarController.navigationItem.leftBarButtonItem = breload;
	
	// [breload release];
	
	// UIBarButtonItem *bwrite = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(toWrite:)];
	
	bwrite = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(toWrite:)];
	
	self.tabBarController.navigationItem.rightBarButtonItem = bwrite;
	
	// [bwrite release];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	
	self.tabBarController.navigationItem.leftBarButtonItem = nil;
	self.tabBarController.navigationItem.rightBarButtonItem = nil;
}

/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	[tweets removeAllObjects];
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	[tweets release];
	self.deflogo = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [tweets count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
#ifdef CUSTOM_CELL
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];		
#else		
		// TODO 如果使用自定义表格元素，就要使用Default样式
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
#endif
		
#ifdef CUSTOM_CELL
		[CustomCellMaker makeCustomCellWithType:CELL_TWEET toCell:cell];
#endif
		
	}
    
    // Set up the cell...
	NSInteger row = indexPath.row;
	Tweet *tt = [tweets objectAtIndex:row];
	if(tt){
#ifdef CUSTOM_CELL
		UIImageView *imgView = (UIImageView *)[cell viewWithTag:0];
		UILabel *lName = (UILabel *)[cell viewWithTag:1];
		UILabel *lDate = (UILabel *)[cell viewWithTag:2];
		UILabel *lTweet = (UILabel *)[cell viewWithTag:3];
		lName.text = tt.usr.screen_name;
		
		
		//NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
//		[inputFormatter setDateFormat:NSDateFormatterStyle];
//		
//		NSDate *date = [inputFormatter dateFromString:tt.created_at];
//		[inputFormatter setDateFormat:@"%m/%d"];
//		lDate.text = [inputFormatter stringFromDate:date];
//		[inputFormatter release];
		NSString *ct = tt.created_at;
		NSString *month = [ct substringWithRange:(NSMakeRange(4, 3))];
		NSString *day = [ct substringWithRange:(NSMakeRange(8, 2))];
		NSString *year = [ct substringWithRange:(NSMakeRange(26, 4))];
		ct = nil;
		ct = [[NSString alloc] initWithFormat:@"%@ %@,%@",month,day,year];
		lDate.text = ct;
		[ct release];
		
		
#ifdef DEBUG
		NSLog(@"%@/%@/%@",year,month,day);  // Fri Jun 04 01:10:17 +0000 2010
#endif		
		
		// lDate.text = tt.created_at;
		lTweet.text = tt.text;
		NSString *img = tt.usr.profile_image_url;
		if(img){			
			UIImage *im = [pp getImage:img];
			if(im){
				imgView.image = im;
			}else{
				imgView.image = self.deflogo;
				[pp loadImage:img];
			}
		}
//		imgView = (UIImageView *)[cell viewWithTag:4];
//		if([tt.favorited boolValue]){
//			imgView.image = self.favYESImage;
//		}else{
//			imgView.image = self.favNOImage;
//		}
#else
		cell.textLabel.text = tt.text;
		cell.detailTextLabel.text = tt.usr.screen_name;
		NSString *img = tt.usr.profile_image_url;
		pp.delegate = self;
		if(img){			
			UIImage *im = [pp getImage:img];
			if(im){
				cell.imageView.image = im;
			}else{
				cell.imageView.image = self.deflogo;
				[pp loadImage:img];
			}
		}
#endif
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		//cell.contentView.backgroundColor = [UIColor lightGrayColor];
	}
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	NSInteger row = indexPath.row;
	Tweet *tw = [tweets objectAtIndex:row];
	if(tw){
		ViewControllerChooser *chooser = [ViewControllerChooser sharedChooser];
		TweetDetailViewController *td = (TweetDetailViewController *)[chooser choose:VC_DETAIL_TWEET];
		td.tweet = tw;
		td.tws = tweets;
		[self.navigationController pushViewController:td animated:YES];
	}
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//	CGFloat ret = 60.0;
//	NSInteger section = indexPath.section;
//	if(section == 0){
//		//NSInteger row = indexPath.r
//	}
//	return ret;
//}



// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
		// [tweets removeObjectAtIndex:indexPath.row];
		NSInteger row = indexPath.row;
		Tweet * tw = [tweets objectAtIndex:row];
		[tweets removeObjectAtIndex:row];
		if(row==0){
			Tweet *td = [tweets objectAtIndex:0];
			if(td){
				lastID = td.tid;
			}
		}
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
		DataManager *dm = [DataManager sharedManager];
		[dm.managedObjectContext deleteObject:tw];
		// [pp removeImage:tw.usr.profile_image_url];		
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}



/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark -
#pragma mark ImageLoad
- (void)imageDidLoadFinished:(NSString *)imgURL{
	[self.tableView reloadData];
}

#pragma mark -

- (void)reload:(id)sender{
	if(!loading){
		loading = YES;
		[NSThread detachNewThreadSelector:@selector(loadTweets:) toTarget:self withObject:nil];
	}	
}

- (void)loadTweets:(id)args{
	TwitterClient *tc = [TwitterClient getInstance];
	if (tc.tokenInfo == nil || tc.tokenInfo.token == nil) {
		NSLog(@"Error NO Auth");
		NSString *token = [tc doOAuthRequestToken];
		NSString *authURL = [[NSString alloc] initWithFormat:@"http://api.twitter.com/oauth/authorize?oauth_token=%@",token];
		NSString *enURL = [GTMBase64 stringByEncodingData:[authURL dataUsingEncoding:NSUTF8StringEncoding]];
		[authURL release];
		[self performSelectorOnMainThread:@selector(oatest:) withObject:enURL waitUntilDone:YES];
		return;
	}
	NSArray *ts = [tc doStatusesHomeTimeLineWithSinceID:lastID];
	// NSArray *ts = [tc doStatusesPublicTimeLine];
	if(ts){
		NSInteger c = [ts count];
		if(c > 0){
			// self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",c];
			[self performSelectorOnMainThread:@selector(reloadTable:) withObject:ts waitUntilDone:NO];
		}else{
			// TODO 如果搜索结果为空 要展现给用户
		}
	}

	loading = NO;
}

- (void)reloadTable:(id)args{
	if(args){
		NSArray *ts = (NSArray *)args;
		NSInteger c = [ts count];
		NSString *bv = self.tabBarController.tabBar.selectedItem.badgeValue;
		NSInteger ibv = [bv intValue];
		ibv += c;
		NSString *sv = [[NSString alloc] initWithFormat:@"%d",ibv];
		self.tabBarItem.badgeValue = sv;
		[sv release];
		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
		// 插入数组到起始位置
		[tweets insertObjects:ts atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, c)]];
		//[tweets addObjectsFromArray:ts];
		[pool release];
		// pool = nil;
		[self.tableView reloadData];
	}
}

- (void)toWrite:(id)sender{
	// TODO 开启发送窗口
	ViewControllerChooser *chooser = [ViewControllerChooser sharedChooser];
	ReplyTweetViewController *rt = (ReplyTweetViewController *)[chooser choose:VC_REPLY_TWEET];
	rt.tweet = nil;
	rt.acType = AC_TYPE_WRITE;
	[self.navigationController pushViewController:rt animated:YES];
}

- (void)oatest:(id)sender{
	ViewControllerChooser *chooser = [ViewControllerChooser sharedChooser];
	AuthorViewController *auvc = (AuthorViewController *)[chooser choose:VC_AUTH];
	auvc.authURL = (NSString *)sender;
	// [self presentModalViewController:auvc animated:YES];
	[self.navigationController pushViewController:auvc animated:YES];
}


- (void)dealloc {
	[tweets release];
	[deflogo release];
	[pp release];
	[breload release];
	[bwrite release];
	[fetchedResultsController release];
	// ---------
	[lastID release];
	[favYESImage release];
	[favNOImage release];
    [super dealloc];
}


@end

